package com.qf.web.filter;

import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
//实现自动登录
    //验证是否登录了，没有登录，则自动登录：如果登录成功，放行
    //1从cookie中获取用户信息，解密
    //2验证码用户名是否正确
    //如果正确，登录成功
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //从session中获取用户信息
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //如果已经登录了，则放行
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            filterChain.doFilter(request,response);
            return;
        }
        //自动登录
        //获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            response.sendRedirect("/login.jsp");
            filterChain.doFilter(request,response);
            return;
        }
        //循环cookie
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            //查找需要的用户信息
            if ("userinfo-2202".equals(name)) {
                String value = cookie.getValue();
                //解密 admin#123456
                String userInfo = Base64Utils.decode(value);
                String[] arr = userInfo.split("#");
                if (arr != null && arr.length == 2) {
                    UserService userService = new UserServiceImpl();
                    User login = userService.login(arr[0], arr[1]);
                    if (login != null) {
                        request.getSession().setAttribute("user",login);
                       // response.sendRedirect("/index.jsp");
                        break;
                    }

                }

            }
        }
        //放行
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
